<template>
  <div class="pieChart">
    <div :class="className" :style="{height: height, width: width}" />
  </div>
</template>
<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import ResizeMixin from './mixins/resize'

export default {
  name: "IotPieChart",
  mixins: [ResizeMixin],
  props: {
    className: {
      default: "chart"
    },
    data: {
      type: Array,
      default: () => []
    },
    width: {
      default: "100%"
    },
    height: {
      default: "320px"
    }
  },
  watch: {
    data: function(newVal, oldVal) {
      if (newVal.length > 0) {
        this.$nextTick(() => {
          this.initChart();
        });
      }
    },
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.initChart();
    // });
  },
  methods: {
    dataChange() {
      return this.data.map(key => key.name);
    },
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.chart.setOption({
        tooltip: {
          show: false,
          trigger: "item",
        },
        legend: {
          orient: 'vertical',
          right: "20",
          top: "25",
          itemWidth: 6,
          itemGap:20,
          data: this.dataChange(),
          icon:"circle",
        },
        series: [
          {
            name: '',
            type: "pie",
            radius: [16, 40],
            center: ["39%", "50%"],
            roseType: 'radius',
            label: {
              formatter: '{b} \n {d}%',
              show: false,
            },
            emphasis: {
              label: {
                show: true
              }
            },
            data: this.data,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              normal:{
                color:function(params) {
                  //自定义颜色
                  var colorList = [
                    '#5584FF', '#9EAEC5', '#FF5757',  '#FF8C00', '#FF0000', '#FE8463',
                  ];
                  return colorList[params.dataIndex]
                }
              }
            },
            animationEasing: "cubicInOut",
            animationDuration: 2600
          }
        ]
      });
    }
  }
}
</script>
<style lang="scss" scope>
.pieChart{
  position: absolute;
  left: 60px;
  top: 210px;
  z-index: 99;
  width: 320px;
  height: 135px;
  opacity: 0.92;
  background: #ffffff;
  border-radius: 6px;
  box-shadow: 0px 2px 12px 0px rgba(0,0,0,0.1);
}
</style>
